const { defineConfig } = require("@vue/cli-service");
const path = require("path");
const fs = require("fs");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");

// const buildConfigs = require('./vue.config.build.json');
// let buildConfig = buildConfigs[process.env.VUE_APP_COMPANY || 'M-Design'].build;

const customization = process.env.VUE_APP_CUSTOMIZATION;
// const customizationBuildConfig = buildConfigs[customization]?.build;

// buildConfig = { ...buildConfig, ...customizationBuildConfig };

const files = [
  "**/*",
  "!statics/arch/projectTemplate/*",
  "!statics/arch/customization/*",
  "!statics/arch/locale/*",
  "!statics/arch/terminology/*"
];

const archTemplateFilter = ["!**/*"];

if (customization) {
  files.push(`statics/arch/customization/${customization}`);
  files.push(`!statics/arch/customization/${customization}/public/**/*`);
  archTemplateFilter.push(`${customization}/public/**/*`);
}

function copyFolderSync(src, dest) {
  // 创建目标文件夹（支持多级目录）
  fs.mkdirSync(dest, { recursive: true }); // ‌:ml-citation{ref="2,8" data="citationList"}

  // 遍历源文件夹
  const _files = fs.readdirSync(src, { withFileTypes: true }); // ‌:ml-citation{ref="2,8" data="citationList"}

  _files.forEach(file => {
    const srcPath = path.join(src, file.name);
    const destPath = path.join(dest, file.name);

    if (file.isDirectory()) {
      // 递归处理子文件夹
      copyFolderSync(srcPath, destPath); // ‌:ml-citation{ref="2,8" data="citationList"}
    } else {
      // 复制文件
      fs.copyFileSync(srcPath, destPath); // ‌:ml-citation{ref="4,7" data="citationList"}
    }
  });
}

function mkDir(dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath);
  }
}
// 在没有主题的情况下要copy 默认主题到.temp文件下
if (process.env.NODE_ENV === "development") {
  const tempDirPath = resolve("./.temp");
  mkDir(tempDirPath);
  const themePath = resolve("./.temp/theme");
  if (!fs.existsSync(themePath)) {
    copyFolderSync(resolve("./theme/Design/"), resolve("./.temp/theme"));
  } else {
    fs.copyFileSync(resolve("./theme/Design/defaultTheme.zip"), resolve("./.temp/theme/defaultTheme.zip"));
  }
}
// const AutoImport = require('unplugin-auto-import/webpack');
// const Components = require('unplugin-vue-components/webpack');
// const { ElementPlusResolver } = require('unplugin-vue-components/resolvers');
// console.log(buildConfig, buildConfig.win_icon, path.join(__dirname, buildConfig.win_icon));
let buildConfig = {};

let company = process.env.VUE_APP_COMPANY ?? "Design";
// 默认读取当前环境下
try {
  buildConfig = require(`./theme/${company}/config.json`);
} catch (error) {
  // 取不到则读取默认
  company = "Design";
  buildConfig = require(`./theme/${company}/config.json`);
}
// log 的相对路径
const winLogo = `./theme/${company}/${buildConfig.images.winLogo}`;
console.log("winLogo", winLogo);
if (!buildConfig) {
  console.error("vue.config.build.json 配置缺失：" + process.env.VUE_APP_COMPANY);
  throw new Error("vue.config.build.json 配置缺失：" + process.env.VUE_APP_COMPANY);
}

function resolve(dir) {
  return path.join(__dirname, dir);
}
module.exports = defineConfig({
  transpileDependencies: [],
  productionSourceMap: false,
  lintOnSave: false, // process.env.NODE_ENV !== 'production',
  parallel: false,
  runtimeCompiler: false,

  pages: {
    index: {
      // page 的入口
      entry: "src/main.ts",
      // 模板来源
      template: process.env.NODE_ENV == "production" ? "public/index-prod.html" : "public/index-dev.html",
      // 在 dist/index.html 的输出
      filename: "index.html",
      title: buildConfig.systemName
    },

    launch: {
      entry: "src/app/launch/main.ts",
      template: process.env.NODE_ENV == "production" ? "public/index-prod.html" : "public/index-dev.html",

      filename: "launch.html",
      title: buildConfig.systemName
    }
    // ...modelPages
  },

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  chainWebpack: config => {
    // config.module.rule("ts").exclude.add(path.resolve(__dirname, "src/modules")).end();
    if (process.env.NODE_ENV === "production") {
      config.plugin("extract-css").tap(args => {
        // console.log(args);
        args[0].ignoreOrder = true;
        return args;
      });
    }
  },
  configureWebpack: config => {
    const alias = config.resolve.alias;
    alias["statics"] = resolve("public/statics");
    console.log("NODE_ENV = " + process.env.NODE_ENV);
    console.log("VUE_APP_VERSION_TYPE = " + process.env.VUE_APP_VERSION_TYPE);

    console.log(config.target);
    // console.log('111', config);
    // config.module.rules.unshift({
    //   test: /\.worker\.ts$/, // ts结尾
    //   use: {
    //     loader: 'worker-loader',
    //     options: {
    //       // name: '[name]:[hash:8].js',
    //       inline: 'fallback', // 开启内联模式,
    //     }
    //   }
    // }, );

    // 关闭css-loader的url转换
    config.module.rules.forEach(it => {
      it.oneOf &&
        it.oneOf.forEach(i => {
          i.use &&
            i.use.forEach(t => {
              if (t.loader && t.loader.includes && (t.loader.includes("\\css-loader") || t.loader.includes("/css-loader"))) {
                t.options.url = false;
              }
            });
        });
    });
    config.output.globalObject = "this";

    // config.module.rules.push({
    //   test: /\.(txt|xml)$/,
    //   use: 'raw-loader'
    // });
    // config.plugins.push(
    //   AutoImport({
    //     resolvers: [ElementPlusResolver()]
    //   }),
    //   Components({
    //     resolvers: [ElementPlusResolver()]
    //   })
    // );
    // 启用文件系统缓存
    // config.cache = {
    //   type: "filesystem"
    // };

    if (process.env.NODE_ENV === "production") {
      // 为生产环境修改配置...
    } else {
      // 为开发环境修改配置...

      // begin ----- 增加eslint时的内存 避免memoryLimit报错-----------
      // const existingForkTsChecker = config.plugins.filter(p => p instanceof ForkTsCheckerWebpackPlugin)[0];
      // // console.log(JSON.stringify(config.module.rules));
      // config.plugins = config.plugins.filter(p => !(p instanceof ForkTsCheckerWebpackPlugin));
      // const forkTsCheckerOptions = existingForkTsChecker.options;
      // forkTsCheckerOptions.typescript.memoryLimit = 8198;
      // config.plugins.push(new ForkTsCheckerWebpackPlugin(forkTsCheckerOptions));

      const tsChecker = config.plugins.find(p => p instanceof ForkTsCheckerWebpackPlugin);
      tsChecker.options.typescript.memoryLimit = 1024 * 8;
      // console.log(JSON.stringify(tsChecker.options, undefined, 2));
      // end ----- 增加eslint时的内存 避免memoryLimit报错  -----------

      // 开发环境使用 cdn 引入依赖，加快构建
      // console.log('externals', config.externals);
      config.externals = config.externals || {};
      // config.externals.vue = "Vue";
      // config.externals['element-plus'] = "ElementPlus";
      // config.externals['element-plus/dist/index.css'] = "{}";

      console.log("externals", config.externals);
      config.watchOptions = {
        ignored: ["**/public/statics/files/locale/**"]
      };
      alias["vue"] = resolve("node_modules/vue");
      alias["lodash"] = resolve("node_modules/lodash");
      alias["lodash-es"] = resolve("node_modules/lodash-es");

      const designGraphPath = resolve("src/mdesign-lib/mdesign-graph.umd.js");
      if (fs.existsSync(designGraphPath)) {
        console.log("use out m-design-graph");
        alias["m-design-graph"] = designGraphPath;
      }
    }
  },
  devServer: {
    static: {
      watch: {
        ignored: "**/public/statics/files/locale/**",
        usePolling: false
      }
    }
  },
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
      builderOptions: {
        appId: "m-design.mbse.com.cn",
        productName: buildConfig.systemName,
        copyright: "Copyright©mbse.com.cn",
        directories: {
          output: "./build" // 输出文件路径
        },
        // asar: false,
        win: {
          // win相关配置
          // icon: buildConfig.win_icon, // 'public/statics/theme/m-design/win-icon256.ico', //  path.join(__dirname, buildConfig.win_icon),
          icon: winLogo, // : "public/icon256.ico",

          // requestedExecutionLevel: "highestAvailable", // asInvoker
          target: [
            {
              target: "dir", // 不打包为安装程序
              arch: [
                "x64" // 64位
                // "ia32", //32位
              ]
            }
          ]
          // artifactName: "${productName}-${version}.${ext}",
        },
        mac: {
          // mac
          //   icon: buildConfig.mac_icon
        },
        files,
        linux: {
          // linux
          //   icon: buildConfig.linux_icon,
          category: "Office",
          // icon: isAclr ? "public/icon-aclr.ico" : "public/icon256.ico",
          // category: 'Office',
          target: [
            {
              target: "dir" // 麒麟
              // arch: [
              // "arm64" // 64位
              // "ia32", //32位
              // ]
            }
          ]
        },
        // 不需要打包到asar包里的文件，需要可以直接访问的
        extraResources: [
          {
            from: "documents/files", // 一些pdf手册和示例项目
            to: "files"
          },
          {
            // 便于调试本地构建
            from: ".temp/nodeServer",
            to: "nodeServer"
          },
          {
            from: ".temp/jre",
            to: "./../jre"
          },
          {
            from: `theme/${company}`,
            to: "theme"
          },
          {
            from: "public/statics/arch/projectTemplate",
            to: "arch/projectTemplate"
          },
          {
            from: "public/statics/arch/customization",
            to: "arch/customization",
            filter: archTemplateFilter
          },
          {
            from: "public/statics/arch/locale",
            to: "arch/locale"
          },
          {
            from: "public/statics/arch/terminology",
            to: "arch/terminology"
          }
          // {
          //   "from": ".temp/database",
          //   "to": "./../database",
          // }
        ]
      }
    }
  }
});
